package cn.rocky.other;

import java.util.ArrayList;
import java.util.Iterator;

public class ArrayListDemo {

    public static void main(String[] args) {
        // 创建 ArrayList 对象
        ArrayList<String> list = new ArrayList<>();

        // 添加元素
        list.add("Java");
        list.add("Python");
        list.add("C++");

        // 获取元素
        System.out.println("第二个元素是：" + list.get(1));

        // 修改元素
        list.set(1, "JavaScript");
        System.out.println("修改后的第二个元素是：" + list.get(1));

        // 删除元素
        list.remove(0);
        System.out.println("删除后的第一个元素是：" + list.get(0));

        System.out.println("for遍历元素：");
        // for
        for (int i = 0; i < list.size(); i++) {
            System.out.print(list.get(i) + " ");
        }

        System.out.println();
        System.out.println("for each 遍历元素：");
        // for each 遍历元素
        for (String s : list) {
            System.out.print(s + " ");
        }

        System.out.println();
        System.out.println("迭代器遍历元素：");
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()) {
            String element = iterator.next();
            System.out.print(element + " ");
        }
    }
}

